#include <rtthread.h>
#include "rtdevice.h"

#include "config.h"
#include "led.h"
#include "mqtt.h"

#define DBG_TAG "led"
#define DBG_LVL DBG_LOG
#include <rtdbg.h>

#define ALERT_LED_PIN   CFG_LED_USED_PIN
#define ALERT_LED_ON    CFG_LED_ON
#define ALERT_LED_OFF   CFG_LED_OFF

static rt_uint8_t g_led_keeping = 1;

static int alert_led_on(void)
{
    rt_pin_write(ALERT_LED_PIN, ALERT_LED_ON);
    LOG_D("alert led on");
    return ALERT_LED_ON;
}

static int alert_led_off(void)
{
    rt_pin_write(ALERT_LED_PIN, ALERT_LED_OFF);
    LOG_D("alert led off");
    return ALERT_LED_OFF;
}

static int get_alert_led_status(void)
{
    return rt_pin_read(ALERT_LED_PIN);
}

static int alert_led_toggle(void)
{
    return (get_alert_led_status() == ALERT_LED_OFF) ? alert_led_on() : alert_led_off();
}

int alert_led_disable(void)
{
    g_led_keeping = 0;
    return RT_EOK;
}

static void alert_led_thread_entry(void *parameter)
{
    rt_sem_t sem = (rt_sem_t)parameter;

    while (1)
    {
        rt_sem_take(sem, RT_WAITING_FOREVER);
        LOG_D("led take ok ...");
        g_led_keeping = 1;
        update_device_status(CFG_ALERT_LED_USED_IDX, CFG_ALERT_LED_ON_VALUE);
        while (g_led_keeping)
        {
            alert_led_toggle();
            rt_thread_mdelay(500);
        }
        alert_led_off();
        LOG_D("led off");
        update_device_status(CFG_ALERT_LED_USED_IDX, CFG_ALERT_LED_OFF_VALUE);
    }
}

int alert_led_init(void *arg)
{
    rt_pin_mode(ALERT_LED_PIN, PIN_MODE_OUTPUT);
    rt_pin_write(ALERT_LED_PIN, ALERT_LED_OFF);
    rt_pin_mode(CFG_LED2_USED_PIN, PIN_MODE_OUTPUT);
    rt_pin_write(CFG_LED2_USED_PIN, ALERT_LED_OFF);
    rt_pin_mode(CFG_LED3_USED_PIN, PIN_MODE_OUTPUT);
    rt_pin_write(CFG_LED3_USED_PIN, ALERT_LED_OFF);

    rt_thread_t thread = rt_thread_create("led_thread", alert_led_thread_entry, arg, 1024, 10, 20);
    if (thread != RT_NULL)
    {
        rt_thread_startup(thread);
        return RT_EOK;
    }
    else
    {
        LOG_E("create led3 thread failed");
        return (-RT_ERROR);
    }
}


